package com.company.oa.workflow.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.company.oa.workflow.dto.ApprovalDTO;
import com.company.oa.workflow.entity.document.ApprovalRecord;
import com.company.oa.workflow.entity.document.ApprovalNode;
import com.company.oa.workflow.entity.document.Document;
import com.company.oa.workflow.mapper.ApprovalNodeMapper;
import com.company.oa.workflow.mapper.ApprovalRecordMapper;
import com.company.oa.workflow.mapper.DocumentMapper;
import com.company.oa.workflow.service.ApprovalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class ApprovalServiceImpl implements ApprovalService {

    @Autowired
    private DocumentMapper documentMapper;

    @Autowired
    private ApprovalNodeMapper nodeMapper;

    @Autowired
    private ApprovalRecordMapper approvalRecordMapper;

    @Override
    public IPage<Map<String, Object>> getTodoTasks(int page, int size, Long userId, String businessType) {
        Page<Document> pageParam = new Page<>(page, size);
        LambdaQueryWrapper<Document> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Document::getCurrentApproverId, userId)
                .eq(Document::getStatus, 1);

        wrapper.orderByDesc(Document::getCreateTime);
        IPage<Document> documentPage = documentMapper.selectPage(pageParam, wrapper);

        // 转换为Map结果
        return documentPage.convert(document -> {
            Map<String, Object> map = new HashMap<>();
            map.put("id", document.getId());
            map.put("title", document.getTitle());
            map.put("createTime", document.getCreateTime());
            map.put("creatorName", document.getCreatorName());
            map.put("status", document.getStatus());
            return map;
        });
    }

    @Override
    public IPage<ApprovalRecord> getDoneTasks(int page, int size, Long userId, String businessType) {
        Page<ApprovalRecord> pageParam = new Page<>(page, size);
        LambdaQueryWrapper<ApprovalRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ApprovalRecord::getApproverId, userId);

        if (businessType != null && !businessType.isEmpty()) {
            wrapper.eq(ApprovalRecord::getBusinessType, businessType);
        }

        wrapper.orderByDesc(ApprovalRecord::getApprovalTime);
        return approvalRecordMapper.selectPage(pageParam, wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean approveTask(ApprovalDTO approvalDTO, Long userId) {
        Document document = documentMapper.selectById(approvalDTO.getDocumentId());
        if (document == null) {
            throw new RuntimeException("公文不存在");
        }

        // 检查公文状态
        if (document.getStatus() != 1) {
            throw new RuntimeException("公文不在审批中状态");
        }

        // 检查当前审批人
        if (!document.getCurrentApproverId().equals(userId)) {
            throw new RuntimeException("您不是当前审批人");
        }

        // 查询当前审批节点
        LambdaQueryWrapper<ApprovalRecord> recordWrapper = new LambdaQueryWrapper<>();
        recordWrapper.eq(ApprovalRecord::getDocumentId, document.getId());
        ApprovalRecord lastRecord = approvalRecordMapper.selectOne(recordWrapper);

        int currentNode = 1;
        if (lastRecord != null) {
            currentNode = lastRecord.getNode() + 1;
        }

        // 保存审批记录
        ApprovalRecord record = new ApprovalRecord();
        record.setDocumentId(document.getId());
        record.setApproverId(userId);
        record.setApprovalTime(LocalDateTime.now());
        approvalRecordMapper.insert(record);

        // 更新公文状态
        if (approvalDTO.getApprovalResult() == 2) {
            // 驳回
            document.setStatus(3);
            document.setCurrentApproverId(null);
            document.setCurrentApproverName(null);
        } else {
            // 通过，查找下一个审批节点
            LambdaQueryWrapper<ApprovalNode> nodeWrapper = new LambdaQueryWrapper<>();
            nodeWrapper.eq(ApprovalNode::getFlowId, document.getApprovalFlowId())
                    .eq(ApprovalNode::getOrderNum, currentNode + 1);
            ApprovalNode nextNode = nodeMapper.selectOne(nodeWrapper);

            if (nextNode == null) {
                // 没有下一个节点，审批完成
                document.setStatus(2);
                document.setCurrentApproverId(null);
                document.setCurrentApproverName(null);
            } else {
                // 设置下一个审批人
                document.setCurrentApproverId(nextNode.getApproverId());
                document.setCurrentApproverName(nextNode.getApproverName());
            }
        }

        document.setUpdateTime(LocalDateTime.now());
        documentMapper.updateById(document);

        return true;
    }

    @Override
    public IPage<ApprovalRecord> getApprovalRecords(int page, int size, String processInstanceId) {
        Page<ApprovalRecord> pageParam = new Page<>(page, size);
        LambdaQueryWrapper<ApprovalRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ApprovalRecord::getProcessInstanceId, processInstanceId);
        return approvalRecordMapper.selectPage(pageParam, wrapper);
    }

    @Override
    public String getProcessDiagram(String processInstanceId) {
        // 实现获取流程图逻辑
        return null;
    }

    @Override
    public Map<String, Object> getTaskDetail(String taskId) {
        // 实现获取任务详情逻辑
        return null;
    }
}